package com.educate.book.rpc.provide.service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.book.dao.ItemDao;
import com.educate.book.model.bo.ItemBO;
import com.educate.book.model.po.Item;
import com.educate.book.rpc.api.ItemService;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.common.web.IdGen;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class ItemServiceImpl implements ItemService {

    @Resource ItemDao itemDao;

    @Override
    public String create(ItemBO bo) {
    	bo.setItemId(IdGen.uuid());
    	bo.setCrateTime(new Timestamp(System.currentTimeMillis()));
    	Item item = itemDao.insert(bo);
    	return item.getItemId();
    }

    @Override
    public void delete(ItemBO bo) {
    	itemDao.delete(bo);
    }

    @Override
    public void delete(String itemId) {
    	itemDao.deleteById(itemId);
    }

    @Override
    public ItemBO detail(String itemId) {
        Optional<Item> optional = itemDao.findById(itemId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new ItemBO(optional.get());
    }

    @Override
    public ItemBO detail(ItemBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(ItemBO bo) {
        Optional<Item> optional = itemDao.findById(bo.getItemId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        itemDao.save(optional.get());
    }

    @Override
    public Page<ItemBO> query(ItemBO bo, PageRequest pageRequest) {
        return itemDao.query(bo, pageRequest).map(ItemBO::new);
    }

    @Override
    public List<ItemBO> list(ItemBO bo) {
        List<Item> result = itemDao.findAll();
        return ListUtils.map(result, ItemBO::new);
    }
}
